<template>
  <Dialog
    ref="refDialog"
    title="多页签章"
    @submit="onSubmit"
    width="420"
    draggable
    textOk="签章"
    @close="onClose"
  >
    <el-form
      ref="refForm"
      @keyup.enter="onSubmit"
      @submit.native.prevent
      :model="formData"
      :rules="formRules"
    >
      <el-radio-group v-model="formData.pageRange" class="block">
        <div>
          <el-radio value="all">所有页</el-radio>
        </div>
        <div class="flex">
          <el-radio value="partial">所选页码</el-radio>
          <el-form-item
            label=" "
            prop="page"
            class="flex-1 ml-[-28px]"
            v-show="formData.pageRange == 'partial'"
          >
            <el-input v-model="formData.page" placeholder="请输入指定页码" />
          </el-form-item>
        </div>
      </el-radio-group>
    </el-form>
    <div
      class="text-light text-xs leading-[20px]"
      v-show="formData.pageRange == 'partial'"
    >
      <p>
        * 如果输入1-3, 5,
        7，系统会在文件的第1到3页、第5页和第7页签章。请按实际需要输入页码范围。
      </p>
    </div>
  </Dialog>
</template>
<script setup>
import { reactive, toRefs, ref, inject } from "vue";

const provideHome = inject("provideHome");
const refDialog = ref();
const refForm = ref();

const state = reactive({
  style: {},
  formData: {
    pageRange: "partial",
    page: "",
  },
});
const { style, formData } = toRefs(state);

const emits = defineEmits(["submit"]);

const formRules = {
  page: [
    {
      validator: (rule, value, callback) => {
        if (state.formData.pageRange == "all") {
          callback();
        } else {
          //指定页码
          if (!value) {
            callback("请输入指定页码");
          } else if (/^[\d,，-]+$/.test(value)) {
            let pages = value.replace(/[-，]/g, ",").split(",");
            //当前文档页码数
            let { numPages } = PDFViewerApplication.pdfDocument;
            let hasError = pages.some(item => {
              return item > numPages;
            });
            if (hasError) {
              callback("最大页码不能超过 " + numPages);
            } else {
              callback();
            }
          } else {
            callback("请按照提示，输入有效的页码");
          }
        }
      },
    },
  ],
};
const onReset = () => {
  refForm.value?.resetFields();
};

const onClose = () => {
  provideHome.methods.setSealCurrentOperateName("");
};

const onSubmit = async () => {
  refForm.value.validate(async valid => {
    if (valid) {
      let { pageRange, page } = state.formData;
      let finalPage = page;
      if (pageRange == "all") {
        finalPage = 0;
      } else {
        finalPage = state.formData.page.replace(/，/g, ",");
      }
      emits("submit", {
        page: finalPage,
      });
    }
  });
  // emits("submit");
};

defineExpose({
  show() {
    onReset();
    refDialog.value.show();
  },
  close() {
    refDialog.value.close();
  },
});
</script>
<style lang="scss"></style>
